<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\madmin\service;

use app\madmin\model\Advert;
use app\madmin\model\Commodity;
use app\madmin\model\LiveGood;
use app\madmin\model\LiveLog;
use app\madmin\model\LiveRoom;
use app\madmin\model\LiveRoomHasGood;
use app\madmin\model\Mytemplate;
use app\madmin\model\Renovation;
use app\madmin\model\Template;
use app\madmin\model\TemplateClassify;
use app\utils\LiveErrorCode;
use app\utils\Wechat;
use shopstar\components\wechat\helpers\MiniProgramBroadcastRoomHelper;
use shopstar\constants\broadcast\BroadcastLogConstant;
use shopstar\constants\broadcast\BroadcastRoomIsDeletedConstant;
use shopstar\models\log\LogModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\HttpException;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Request;
use think\swoole\websocket\Room;

class LiveRoomService
{


    /**列表
     * @param array $data
     * @return array
     * @throws DbException
     */
    public function list($page, $size)
    {

        $where = [];
        $data = request()->get();
        !empty($data['name']) && $where[] = ['anchor_wechat|title|anchor_name', 'like', '%' . $data['name'] . '%'];
        !empty($data['status']) && $where[] = ['status', '=', $data['status']];
        !empty($data['start_time']) && $where[] = ['start_time', '>=', $data['start_time']];
        !empty($data['end_time']) && $where[] = ['end_time', '<=', $data['end_time']];
        $where[] = ['is_hide', '=', 0];
        $where[] = ['is_delete', '=', 0];

        $res = LiveRoom::with(["liveGoods"])->where($where)->order('status','asc')->paginate(['page' => $page, 'list_rows' => $size]);
        foreach ($res as $item) {
            foreach ($item->liveGoods as $liveGood) {
                $liveGood['goods'] = Commodity::where(['id' => $liveGood->goods_id])->field(['id',
                    'merchant_id',
                    'type',
                    'name',
                    'subtitle',
                    'master',
                    'classify_id',
                    'total',
                    'sell',
                    'original_price',
                    'sell_price',
                    'min_price',
                    'max_price',
                    'sort',
                    'is_virtual',
                    'virtual_sell',
                    'is_distribution',
                    'distribution',
                    'has_sku',
                    'audit',
                    'status',
                    'create_time',
                    'update_time'])->find();
            }
        }


        return [HTTP_SUCCESS, $res];
    }

    /**直播详情
     * @param int $id
     * @return int
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     */
    public function detail(int $id)
    {
        $find = LiveRoom::with(["liveGoods" => function ($query) {
            $query->with('goods');
        }])->find($id);
        return [HTTP_SUCCESS, $find];
    }

    /**直播回放
     * @param int $id
     * @return int
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     */
    public function getReplay(int $id)
    {
        $start = request()->get('start', 0);
        $limit = request()->get('limit', 10);
        $data = [
            'action' => 'get_replay',
            'room_id' => $id,
            'start' => $start,
            'limit' => $limit
        ];

        $result = \app\utils\LiveRoom::getReplay($data);

        $err_msg = LiveErrorCode::getError($result);

        if (!empty($err_msg)) return [HTTP_NOTACCEPT, $err_msg];

        return [HTTP_SUCCESS, $result];
    }

    /** 生成二维码
     * @param $merchant_id
     * @param $page_type
     * @param $pid
     * @return string
     */
    private function getQrcode($id)
    {
        $result = \app\utils\LiveRoom::getShareCode(['roomId' => $id]);
        $err_msg = LiveErrorCode::getError($result);
        if (!empty($err_msg)) {
            return [HTTP_NOTACCEPT, $err_msg];
        }
        return [HTTP_SUCCESS, $result];
    }

    /**添加直播间
     * @param array $data
     * @return array
     */
    public function add()
    {

        global $user;
        $data = request()->post();
        $item = [];
        Db::startTrans();
        try {
            $cover_img_media=Wechat::uploadImage($data['cover_img']);
            $share_img_media=Wechat::uploadImage($data['share_img']);

            $err_msg = LiveErrorCode::getError($cover_img_media);
            if (!empty($err_msg)) {
                return [HTTP_NOTACCEPT, $err_msg];
            }

            $cover_img_media_id =$cover_img_media['media_id'];
            $share_img_media_id = $share_img_media['media_id'];
            $data = array_merge($data, [
                'media_id' => $cover_img_media_id,
                'share_img_media_id' => $share_img_media_id,
            ]);
            $model = new LiveRoom();
            setAttributes($model, $data);

            if (strtotime($data['start_time']) < strtotime('+10 minute')) {
                return [HTTP_NOTACCEPT, "开播时间需要在当前时间的10分钟后"];
            }
            $intervals = strtotime($data['end_time']) - strtotime($data['start_time']);


            if ($intervals < 30 * 60 || $intervals > 60 * 60 * 24) {
                return [HTTP_NOTACCEPT, "开播时间和结束时间间隔不得短于30分钟，不得超过24小时"];
            }


            //创建微信小程序直播间
            $roomResult = \app\utils\LiveRoom::create([
                'name' => mb_substr($model->title, 0, 31) . (mb_strlen($model->title) > 31 ? '...' : ''), //直播间名称
                'coverImg' => $model->media_id, //背景图
                'startTime' => strtotime($model->start_time),
                'endTime' => strtotime($model->end_time),
                'feedsImg' => $model->media_id,//封面图
                'anchorName' => $model->anchor_name ?? '',//主播昵称
                'anchorWechat' => $model->anchor_wechat ?? '',//主播微信号
                'shareImg' => $model->share_img_media_id ?? '',//分享图片
                'type' => (int)$model->room_type ?? 0,//直播类型
                'screenType' => (int)$model->screen_type ?? 0,//
                'closeLike' => (int)$model->close_like ?? 0,//
                'closeGoods' => (int)$model->close_goods ?? 0,//
                'closeComment' => (int)$model->close_comment ?? 0,//
                'closeReplay' => (int)$model->close_replay ?? 0,//
                'closeShare' => (int)$model->close_share ?? 0,//
                'isFeedsPublic' => (int)$model->is_feeds_public ?? 1,//
            ]);

            if (!empty($roomResult['errmsg'])) {

                throw new \Exception(LiveErrorCode::getError($roomResult));
            }
            $model->mall_id = $user->mall_id;
            $model->room_id = $roomResult['roomId'];
            $model->save();
            Db::commit();
            LiveLog::write(
                '添加直播间',
                [
                    'log_data' => json_encode($model, JSON_UNESCAPED_UNICODE),
                    'log_primary' => [
                        '直播间id' => $model->id,
                        '直播间名称' => $model->title,
                        '主播昵称' => $model->anchor_name,
                        '开播时间' => $model->start_time,
                        '结束时间' => $model->end_time,
                    ]
                ],
                $model->id
            );

        } catch (\Exception $e) {
            Db::rollback();
            return [HTTP_NOTACCEPT, $e->getMessage()];
        }
        return [HTTP_SUCCESS, $model];
    }

    /**编辑直播间
     * @param array $data
     * @return array
     */
    public function edit($id)
    {
        $model = LiveRoom::find($id);
        if (empty($model)) {
            return [HTTP_NOTACCEPT, "直播间不存在"];
        }
        $data = request()->post();
        Db::startTrans();
        try {

            $cover_img_media_id = empty($data['cover_img']) ? $model->media_id : ( $data['cover_img']== $model->cover_img ? $model->media_id :  Wechat::uploadImage($data['cover_img'])['media_id']);
            $share_img_media_id = empty($data['share_img']) ? $model->share_img_media_id : ( $data['share_img']== $model->share_img ? $model->share_img_media_id : Wechat::uploadImage($data['share_img'])['media_id']);
            $data = array_merge($data, [
                'media_id' => $cover_img_media_id,
                'share_img_media_id' => $share_img_media_id,
            ]);
            setAttributes($model, $data);

            //创建微信小程序直播间
            $roomResult = \app\utils\LiveRoom::editRoom([
                'id' => $model->room_id,
                'name' => mb_substr($model->title, 0, 31) . (mb_strlen($model->title) > 31 ? '...' : ''), //直播间名称
                'coverImg' => $model->media_id, //背景图
                'startTime' => strtotime($model->start_time),
                'endTime' => strtotime($model->end_time),
                'feedsImg' => $model->media_id,//封面图
                'anchorName' => $model->anchor_name ?? '',//主播昵称
                'anchorWechat' => $model->anchor_wechat ?? '',//主播微信号
                'shareImg' => $model->share_img_media_id ?? '',//分享图片
                'type' => (int)$model->room_type ?? 0,//直播类型
                'screenType' => (int)$model->screen_type ?? 0,//
                'closeLike' => (int)$model->close_like ?? 0,//
                'closeGoods' => (int)$model->close_goods ?? 0,//
                'closeComment' => (int)$model->close_comment ?? 0,//
                'closeReplay' => (int)$model->close_replay ?? 0,//
                'closeShare' => (int)$model->close_share ?? 0,//
                'isFeedsPublic' => (int)$model->is_feeds_public ?? 1,//
            ]);
            if (!empty($roomResult['errmsg'])) {
                throw new \Exception(LiveErrorCode::getError($roomResult));
            }
            $model->save();
            Db::commit();
            LiveLog::write(
                '编辑直播间',
                [
                    'log_data' => json_encode($model, JSON_UNESCAPED_UNICODE),
                    'log_primary' => [
                        '直播间id' => $model->id,
                        '直播间名称' => $model->title,
                        '主播昵称' => $model->anchor_name,
                        '开播时间' => $model->start_time,
                        '结束时间' => $model->end_time,
                    ]
                ],
                $model->id
            );
        } catch (\Exception $e) {
            Db::rollback();
            return [HTTP_NOTACCEPT, $e->getMessage()];
        }
        return [HTTP_SUCCESS, $model];
    }


    /**同步直播间
     * @param int $id
     * @return int
     */
    public function syncRoom()
    {
        //获取店铺下的所有的直播间
        $start = 0;
        $limit = 100;
        $roomList = [];
        while (true) {
            $roomListResult = \app\utils\LiveRoom::getLiveInfo([
                'start' => $start,
                'limit' => $limit
            ]);
            $err_msg = LiveErrorCode::getError($roomListResult);
            if (!empty($err_msg)) {
                return [HTTP_NOTACCEPT, $err_msg];
            }
            if (empty($roomListResult)) {
                break;
            }

            $roomList = array_merge($roomList, $roomListResult['room_info']);
            //如果小于limit就说明没有下一页了
            if (count($roomListResult['room_info']) <= $limit) {
                break;
            }
            $start += $limit;
        }
        $roomId = [];

        foreach ((array)$roomList as $item) {
            $model = LiveRoom::where(['room_id' => $item['roomid']])->find();
            $data = [
                'room_id' => $item['roomid'],
                //标题
                'title' => $item['name'],
                //主播昵称
                'anchor_name' => $item['anchor_name'],
                //开始时间
                'start_time' => date('Y-m-d H:i:s', $item['start_time']),
                //结束时间
                'end_time' => date('Y-m-d H:i:s', $item['end_time']),
                //状态
                'status' => $item['live_status'],
                //背景图
                'cover_img' => $item['cover_img'],
                //分享图
                'share_img' => $item['share_img'],
                'close_like' => $item['close_like'],
                'close_goods' => $item['close_goods'],
                'close_comment' => $item['close_comment'],
                'live_type' => $item['live_type'],

            ];
            if (empty($model)) {
                $data['create_time'] = date("Y-m-d H:i:s");
                $model = LiveRoom::create($data);
            } else {
                setAttributes($model, $data);
                $model->save();
            }
            #里面还涉及商品的信息不过比较难同步

            $roomId[] = $model->id;
            LiveLog::write(
                '同步直播间',
                [
                    'log_data' => json_encode($model, JSON_UNESCAPED_UNICODE),
                    'log_primary' => [
                        '直播间id' => $model->id,
                        '直播间名称' => $model->title,
                        '主播昵称' => $model->anchor_name,
                        '开播时间' => $model->start_time,
                        '结束时间' => $model->end_time,
                    ]
                ],
                $model->id
            );
        }

        //把不存在的直播间修改为已删除
        if (!empty($roomId)) {
            LiveRoom::whereNotIn('id', implode(",", $roomId))->update(['is_delete' => 1]);
        }

        return [HTTP_SUCCESS, 'success'];
    }


    /**
     * 隐藏直播间
     * @param array $data
     * @return array
     * @throws DbException
     */
    public function hide($id)
    {
        $status = request()->post('status');
        if (!in_array($status, [0, 1])) {
            return [HTTP_NOTACCEPT, '请求参数异常'];
        }
        $model = LiveRoom::update(['is_hide' => $status], ['id' => $id]);
        LiveLog::write(
            '隐藏直播间',
            [
                'log_data' => $model->getData(),
                'log_primary' => [
                    '直播间id' => $model->id,
                    '直播间名称' => $model->title,
                ]
            ],
            $model->id
        );
        return [HTTP_SUCCESS, $model];
    }

    /**
     * 删除直播间
     * @param array $data
     * @return array
     * @throws DbException
     */
    public function delete($id)
    {
        $model = LiveRoom::where(['room_id' => $id])->find();
        if (empty($model)) {
            return [HTTP_NOTACCEPT, '直播间不存在'];
        }
        $result = \app\utils\LiveRoom::deleteRoom(['id' => $id]);

        $err_msg = LiveErrorCode::getError($result);
        if (!empty($err_msg)) {
            return [HTTP_NOTACCEPT, $err_msg];
        }

        //删除商品映射
        LiveRoomHasGood::where(['room_id' => $id])->delete();
        LiveRoom::where(['room_id' => $id])->delete();

        LiveLog::write(
            '删除直播间',
            [
                'log_data' => $model->getData(),
                'log_primary' => [
                    '直播间id' => $model->id,
                    '直播间名称' => $model->title,
                ]
            ],
            $model->id
        );
        return [HTTP_SUCCESS, $model];
    }

    /**
     * 开启/关闭直播间官方收录
     * @param array $data
     * @return array
     * @throws DbException
     */
    public function updateFeedPublic($id)
    {
        $status = request()->post('status');
        if (!in_array($status, [0, 1])) {
            return [HTTP_NOTACCEPT, '请求参数异常'];
        }
        $model = LiveRoom::where(['room_id' => $id])->find();

        if (empty($model)) {
            return [HTTP_NOTACCEPT, '直播间不存在'];
        }
        $model->is_feeds_public = $status;
        $model->save();
//        $model = LiveRoom::update(['is_feeds_public' => $status], ['room_id' => $id]);
        $data = [
            'roomId' => $id,
            'isFeedsPublic' => $status
        ];
        $result = \app\utils\LiveRoom::updateFeedPublic($data);

        $err_msg = LiveErrorCode::getError($result);
        if (!empty($err_msg)) {
            return [HTTP_NOTACCEPT, $err_msg];
        }

        LiveLog::write(
            $status == 1 ? '开启官方收录' : '关闭官方收录',
            [
                'log_data' => $model->getData(),
                'log_primary' => [
                    '直播间id' => $model->id,
                    '直播间名称' => $model->title,
                ]
            ],
            $model->id
        );
        return [HTTP_SUCCESS, $model];
    }

    /**
     * 开启/关闭回放功能
     * @param array $data
     * @return array
     * @throws DbException
     */
    public function updateReplay($id)
    {
        $status = request()->post('status');
        if (!in_array($status, [0, 1])) {
            return [HTTP_NOTACCEPT, '请求参数异常'];
        }
        $model = LiveRoom::update(['close_replay' => $status], ['room_id' => $id]);
        $data = [
            'roomId' => $id,
            'closeReplay' => $status
        ];
        $result = \app\utils\LiveRoom::updateReplay($data);

        $err_msg = LiveErrorCode::getError($result);
        if (!empty($err_msg)) {
            return [HTTP_NOTACCEPT, $err_msg];
        }

        LiveLog::write(
            $status == 0 ? '开启回放功能' : '关闭回放功能',
            [
                'log_data' => $model->getData(),
                'log_primary' => [
                    '直播间id' => $model->id,
                    '直播间名称' => $model->title,
                ]
            ],
            $model->id
        );
        return [HTTP_SUCCESS, $model];
    }

    /**
     * 上下架商品
     * @param array $data
     * @return array
     * @throws DbException
     */
    public function goodsOnSale($id)
    {
        $status = request()->post('status',1);
        if (!in_array($status, [0, 1])) {
            return [HTTP_NOTACCEPT, '请求参数异常'];
        }
        $model = LiveRoom::where(['room_id' => $id])->find();
        if (empty($model)) {
            return [HTTP_NOTACCEPT, '直播间不存在'];
        }
        $goods_id = request()->post('room_goods_id');

        $liveRoomHasGood=LiveRoomHasGood::where(['room_id' => $model->id, 'goods_id' => $goods_id])->find();

        $liveRoomHasGood->is_sale=$status;
        $liveRoomHasGood->save();

        $data = [
            'roomId' => $id,
            'goodsId' => $goods_id,
            'onSale' => $status
        ];
        $result = \app\utils\LiveRoom::goodsOnSale($data);

        $err_msg = LiveErrorCode::getError($result);
        if (!empty($err_msg)) {
            return [HTTP_NOTACCEPT, $err_msg];
        }

        LiveLog::write(
            $status == 1 ? '商品上架' : '商品下架',
            [
                'log_data' => $model->getData(),
                'log_primary' => [
                    '直播间id' => $model->id,
                    '直播间名称' => $model->title,
                    '商品ID' => $goods_id
                ]
            ],
            $model->id
        );
        return [HTTP_SUCCESS, $model];
    }

    /**
     * 添加直播间商品
     * @param array $data
     * @return array
     * @throws DbException
     */
    public function addRoomGoods($id)
    {
        $goods_ids = request()->post('room_goods_ids');
        if (!empty($goods_ids)) {
            if (is_string($goods_ids)) $goods_ids = explode(",", $goods_ids);
        }
        $model = LiveRoom::where(['room_id' => $id])->find();
        if (empty($model)) {
            return [HTTP_NOTACCEPT, '直播间不存在'];
        }
        $data = [
            'roomId' => $id,
            'ids' => $goods_ids,
        ];

        $result = \app\utils\LiveRoom::addGoods($data);


        $err_msg = LiveErrorCode::getError($result);

        if (!empty($err_msg)) {
            return [HTTP_NOTACCEPT, $err_msg];
        }

        foreach ($goods_ids as $goods_id) {
            $liveGood = LiveGood::where(['room_goods_id' => $goods_id])->find();

            $roomHasGoodMode = LiveRoomHasGood::where(['room_id' => $id, 'room_goods_id' => $goods_id])->find();
            if (!$roomHasGoodMode) {
                $roomHasGoodMode = new LiveRoomHasGood();
                $roomHasGoodMode->room_goods_id = !empty($liveGood->id) ? $liveGood->id : 0;
                $roomHasGoodMode->goods_id = $goods_id;
                $roomHasGoodMode->room_id = $model->id;
                $roomHasGoodMode->mall_id = $model->mall_id;
                $roomHasGoodMode->save();
            }
        }

        LiveLog::write(
            "导入直播间商品",
            [
                'log_data' => $model->getData(),
                'log_primary' => [
                    '直播间id' => $model->id,
                    '直播间名称' => $model->title,
                ]
            ],
            $model->id
        );
        return [HTTP_SUCCESS, $model];
    }

    /**
     * 删除直播间商品
     * @param array $data
     * @return array
     * @throws DbException
     */
    public function deleteRoomGoods($id)
    {
        $goods_id = request()->post('room_goods_id');
        $model = LiveRoom::where(['room_id' => $id])->find();
        if (empty($model)) {
            return [HTTP_NOTACCEPT, '直播间不存在'];
        }
        $data = [
            'roomId' => $id,
            'goodsId' => $goods_id,
        ];
        LiveRoomHasGood::where(['room_id' => $model->id, 'goods_id' => $goods_id])->delete();

        $result = \app\utils\LiveRoom::delInRoomGoods($data);

        $err_msg = LiveErrorCode::getError($result);

        if (!empty($err_msg)) {
            return [HTTP_NOTACCEPT, $err_msg];
        }
        LiveLog::write(
            "删除直播间商品",
            [
                'log_data' => $model->getData(),
                'log_primary' => [
                    '直播间id' => $model->id,
                    '直播间名称' => $model->title,
                    '商品ID' => $goods_id
                ]
            ],
            $model->id
        );
        return [HTTP_SUCCESS, $model];
    }

    /**
     * 推送商品
     * @param array $data
     * @return array
     * @throws DbException
     */
    public function pushRoomGoods($id)
    {
        $goods_id = request()->post('room_goods_id');
        $model = LiveRoom::where(['room_id' => $id])->find();
        if (empty($model)) {
            return [HTTP_NOTACCEPT, '直播间不存在'];
        }
        $data = [
            'roomId' => $id,
            'goodsId' => $goods_id,
        ];
        $result = \app\utils\LiveRoom::pushGoods($data);

        $err_msg = LiveErrorCode::getError($result);
        if (!empty($err_msg)) {
            return [HTTP_NOTACCEPT, $err_msg];
        }
        LiveLog::write(
            "推送直播间商品",
            [
                'log_data' => $model->getData(),
                'log_primary' => [
                    '直播间id' => $model->id,
                    '直播间名称' => $model->title,
                    '商品ID' => $goods_id
                ]
            ],
            $model->id
        );
        return [HTTP_SUCCESS, $model];
    }
}